<template>
    <div style="padding: 0px 10px; min-height: 100vh;width: 210mm;margin: 0 auto; background-color: #FFF;">
        <div class="header" style="display: flex;justify-content: space-between;padding-top: 20px;">
            <el-button type="primary" icon="el-icon-back" @click="goBock">返回</el-button>
            <span>
                <el-button type="" icon="el-icon-plus" v-if="!isView" @click="addItem">新增异动项</el-button>
                <el-button type="success" icon="el-icon-check" v-if="!isView" @click="saveData">保存</el-button>
                <el-button type="primary" icon="el-icon-menu" @click="goToList">列表</el-button>
                <!-- <button @click="printToPDF">打印PDF</button> -->
                <el-button type="danger" icon="el-icon-delete" v-if="!isView" @click="deleteSelected">删除选中</el-button>

                <el-button type="info" icon="el-icon-printer" @click="printForm">打印</el-button>
            </span>
        </div>
        <div id="pdf-content">
            <h2 v-if="!editMonth"> <input v-model="month" style="border-bottom: 1px solid;width: 50px;" type="text"
                    :readonly="isView" id="">月份人事异动令</h2>
            <input v-if="editMonth" v-model="month" type="text" placeholder="请输入月份" :readonly="isView">
            <h3>企管（<input v-model="number" type="text" style="width: 40px;" :readonly="isView"> ）字第 <input
                    v-model="serialNumber" type="text" style="width: 40px;" :readonly="isView"> 号</h3>
            <table class="personnel-change-table">
                <thead>
                    <tr>
                        <th class="checkbox" v-if="!isView"><input type="checkbox" v-model="isAllSelected"
                                @change="toggleSelectAll">
                        </th>
                        <th>NO</th>
                        <th>工号</th>
                        <th>姓名</th>
                        <th>原部门</th>
                        <th>原职位</th>
                        <th>新部门</th>
                        <th>新职位</th>
                        <th>生效日期</th>
                        <th>备注</th>
                    </tr>
                </thead>
                <tbody>
                    <tr v-for="(item, index) in personnelChangeList" :key="index">
                        <td class="checkbox" v-if="!isView"><input type="checkbox" v-model="selectedIndices"
                                :value="index"></td>
                        <td>{{ index + 1 }}</td>
                        <td><input v-model="item.employeeId" :readonly="isView"></td>
                        <td><input v-model="item.name" :readonly="isView"></td>
                        <td><input v-model="item.originalDepartment" :readonly="isView"></td>
                        <td><input v-model="item.originalPosition" :readonly="isView"></td>
                        <td><input v-model="item.newDepartment" :readonly="isView"></td>
                        <td><input v-model="item.newPosition" :readonly="isView"></td>
                        <td><input type="date" v-model="item.effectiveDate" :readonly="isView"></td>
                        <td><input v-model="item.remarks" :readonly="isView"></td>
                    </tr>
                </tbody>
            </table>
            <div style="display: flex; justify-content: space-around; margin-top: 10px;">
                <div>
                    <label>审核：</label>
                    <input style="border-bottom: 1px solid;width: 150px;" v-model="reviewer" type="text"
                        :readonly="isView">
                </div>
                <div>
                    <label>核准：</label>
                    <input style="border-bottom: 1px solid;width: 150px;" v-model="approver" type="text"
                        :readonly="isView">
                </div>
            </div>
            <p style="display: flex;justify-content: space-between;"><span>表单编号及版本：AM-JY-189 B/0
                </span><span>保存期限：长期</span></p>
        </div>
    </div>
</template>

<script>
import html2canvas from 'html2canvas';
import jsPDF from 'jspdf';
import { savePersonnelChange, getPersonnelChangeById } from '@/api/personnel';
import { formatDateTime, formatDate, DATE_FORMAT } from '@/utils/date';

export default {
    data() {
        return {
            personnelChangeList: [
                {
                    employeeId: '',
                    name: '',
                    originalDepartment: '',
                    originalPosition: '',
                    newDepartment: '',
                    newPosition: '',
                    effectiveDate: '',
                    remarks: ''
                }
            ],
            selectedIndices: [],
            isAllSelected: false,
            month: '',
            number: '',
            serialNumber: '',
            reviewer: '',
            approver: '',
            editMonth: false,
            isView: false,
            id: null
        };
    },
    created() {
        const { id, type } = this.$route.query;
        if (id) {
            this.id = id;
            this.fetchData(id);
            this.isView = type === 'view';
        }
    },
    watch: {
        selectedIndices(newVal) {
            this.isAllSelected = newVal.length === this.personnelChangeList.length;
        }
    },
    methods: {
        printForm() {
            window.print()
        },
        async fetchData(id) {
            try {
                const result2 = await getPersonnelChangeById(id);
                const result = result2.data;
                if (result.data) {
                    const data = result.data;
                    this.month = data.monthValue;
                    this.number = data.docNumber;
                    this.serialNumber = data.serialNumber;
                    this.reviewer = data.reviewer;
                    this.approver = data.approver;
                    // 格式化日期
                    this.personnelChangeList = (data.personnelChangeList || []).map(item => {
                        return {
                            ...item,
                            effectiveDate: formatDate(item.effectiveDate, DATE_FORMAT.date)
                        };
                    });
                }
            } catch (error) {
                console.error('获取数据失败', error);
                this.$message.error('获取数据失败');
            }
        },
        async saveData() {
            try {
                // 数据验证
                if (!this.month) {
                    this.$message.error('月份不能为空');
                    return;
                }
                if (!this.personnelChangeList.length) {
                    this.$message.error('至少需要一条人事异动记录');
                    return;
                }

                for (const item of this.personnelChangeList) {
                    if (!item.employeeId) {
                        this.$message.error('工号不能为空');
                        return;
                    }
                    if (!item.name) {
                        this.$message.error('姓名不能为空');
                        return;
                    }
                    if (!item.originalDepartment) {
                        this.$message.error('原部门不能为空');
                        return;
                    }
                    if (!item.newDepartment) {
                        this.$message.error('新部门不能为空');
                        return;
                    }
                    if (!item.effectiveDate) {
                        this.$message.error('生效日期不能为空');
                        return;
                    }
                }

                const data = {
                    id: this.id,
                    monthValue: this.month,
                    docNumber: this.number,
                    serialNumber: this.serialNumber,
                    reviewer: this.reviewer,
                    approver: this.approver,
                    personnelChangeList: this.personnelChangeList

                    // 格式化日期
                    // personnelChangeList : (this.personnelChangeList || []).map(item => {
                    //     return {
                    //         ...item,
                    //         effectiveDate: formatDate(item.effectiveDate,DATE_FORMAT.date)
                    //     };
                    // })

                };
                // console.log(data);
                const result = await savePersonnelChange(data);
                if (result) {
                    this.$message.success('保存成功');
                    this.$router.push('/main/renshi/renshizhidu/yfrsyidong/yfrsyidongList');
                }
            } catch (error) {
                console.error('保存失败', error);
                this.$message.error('保存失败');
            }
        },
        printToPDF() {
            const doc = new jsPDF('p', 'pt', 'a4');
            const element = document.querySelector('#pdf-content');
            html2canvas(element).then((canvas) => {
                const imgData = canvas.toDataURL('image/png');
                const imgWidth = 522;
                const pageHeight = 841.89;
                const imgHeight = (canvas.height * imgWidth) / canvas.width;
                let positionY = 10;
                if (imgHeight >= pageHeight) {
                    let leftHeight = imgHeight;
                    while (leftHeight >= pageHeight) {
                        doc.addImage(imgData, 'PNG', 40, positionY, imgWidth, pageHeight);
                        positionY += pageHeight;
                        doc.addPage();
                        leftHeight -= pageHeight;
                    }
                    doc.addImage(imgData, 'PNG', 40, positionY, imgWidth, leftHeight);
                } else {
                    doc.addImage(imgData, 'PNG', 40, positionY, imgWidth, imgHeight);
                }
                doc.save('月份人事异动令.pdf');
            });
        },
        goBock() {
            this.$router.push('/main/renshi/renshizhidu')
        },
        goToList() {
            this.$router.push('/main/renshi/renshizhidu/yfrsyidong/yfrsyidongList')
        },
        addItem() {
            this.personnelChangeList.push({
                employeeId: '',
                name: '',
                originalDepartment: '',
                originalPosition: '',
                newDepartment: '',
                newPosition: '',
                effectiveDate: '',
                remarks: ''
            });
        },
        toggleSelectAll() {
            if (this.isAllSelected) {
                this.selectedIndices = Array.from({ length: this.personnelChangeList.length }, (_, i) => i);
            } else {
                this.selectedIndices = [];
            }
        },
        deleteSelected() {
            this.selectedIndices.sort((a, b) => b - a).forEach(index => {
                this.personnelChangeList.splice(index, 1);
            });
            this.selectedIndices = [];
            this.isAllSelected = false;
        }
    }
};
</script>

<style scoped>
table {
    border-collapse: collapse;
    width: 100%;
}

th,
td {
    border: 1px solid black;
    padding: 3px;
}

p {
    text-align: left;
    line-height: 30px;
}

/* button {
    margin-top: 10px;
    margin-right: 10px;
    padding: 5px 10px;
    cursor: pointer;
    background-color: #409EFF;
    color: white;
    border: none;
    border-radius: 4px;
}

button:hover {
    background-color: #66b1ff;
}

button:disabled {
    background-color: #a0cfff;
    cursor: not-allowed;
} */

input {
    background-color: transparent;
    font-size: 18px;
    font-family: '宋体';
    border: 0px;
    width: 100%;
}

input[type="checkbox"] {
    width: auto;
}

input:disabled {
    color: #606266;
    cursor: not-allowed;
}

@media print {

    body,
    html {
        margin: 0;
        padding: 0;
    }

    .el-button {
        display: none !important;
    }

    .checkbox {
        display: none;
    }

    .leave-adjustment-form {
        margin: 0;
        padding: 0;
        page-break-inside: avoid;
    }

    table {
        page-break-inside: avoid;
        border-collapse: collapse;
        box-shadow: none;
    }

    table th,
    table td {
        border: 1px solid #000;
    }

    input,
    textarea {
        border: none !important;
        background-color: transparent !important;
        text-align: center;
        resize: none;
    }

    .instructions {
        page-break-before: avoid;
    }
}
</style>